package com.pro.admin.web.guanwang;


import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pro.admin.annotation.RequiresPermissionsDesc;
import com.pro.admin.web.BaseController;
import com.pro.core.util.ResponseUtil;
import com.pro.core.validator.NotNullValidator;
import com.pro.db.domain.GuopuBanner;
import com.pro.db.service.itf.IGuopuBannerService;
import com.pro.db.service.itf.IGuopuCategoryRichtextService;
import com.pro.db.service.itf.IGuopuCategoryService;
import com.pro.db.service.itf.IGuopuSettingService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.baidu.unbiz.fluentvalidator.ResultCollectors.toComplex;

/**
 * <p>
 * 轮播图 前端控制器
 * </p>
 *
 * @author wanglei
 * @since 2019-12-22
 */
@RestController
@RequestMapping("/admin/banner")
public class GuopuBannerController extends BaseController {
    private final Log logger = LogFactory.getLog(GuopuBannerController.class);

    @Autowired
    private IGuopuCategoryRichtextService richtextService;

    @Autowired
    private IGuopuCategoryService categoryService;

    @Autowired
    private IGuopuSettingService settingService;

    @Autowired
    private IGuopuBannerService bannerService;

    /**
     * @apiDefine banner 轮播图接口
     *
     */

    /**
     * @api {GET} /admin/banner/list 4.1 获取各栏目或站点轮播图
     * @apiName banner list
     * @apiGroup banner
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     * 栏目ID 和 站点ID 二选一 (不要两个都传)
     *
     * @apiParam {int} categoryId 栏目ID  （二选一）
     * @apiParam {int} siteId 站点ID （二选一）
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:banner:list")
    @RequiresPermissionsDesc(menu={"轮播图管理" , "轮播图设置"}, button="轮播图列表")
    @GetMapping("/list")
    public Object list(Integer categoryId,Integer siteId,
                             @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer size) {
        Page<GuopuBanner> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        IPage<GuopuBanner> pList = bannerService.page(pageVo,
                new QueryWrapper<GuopuBanner>()
                        .eq(categoryId!=null,"category_id",categoryId)
                        .eq(siteId!=null,"site_Id",siteId)
                        .eq("deleted",0)
                        .eq("push_status",1)
                        .orderByDesc("push_sort"));

        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }


    /**
     * @api {GET} /admin/banner/read 4.2 轮播图详情
     * @apiName banner read
     * @apiGroup banner
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 轮播图id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:banner:read")
    @RequiresPermissionsDesc(menu={"轮播图管理" , "轮播图设置"}, button="轮播图详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        GuopuBanner banner = bannerService.getById(id);
        return ResponseUtil.ok(banner);
    }

    /**
     * @api {POST} /admin/banner/create 4.3 新增轮播图
     * @apiName banner create
     * @apiGroup banner
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} categoryId 栏目ID（只有主栏目需要设置轮播图）
     * @apiParam {String} imgUrl 图片地址
     * @apiParam {int} [pushStatus] 是否展示（默认展示1，不展示0）
     * @apiParam {int} [pushSort] 展示顺序（越大越靠前，默认最大10000）
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:banner:create")
    @RequiresPermissionsDesc(menu={"轮播图管理" , "轮播图设置"}, button="新增轮播图")
    @PostMapping("/create")
    public Object create(@RequestBody GuopuBanner banner) {
        ComplexResult check = FluentValidator.checkAll()
                .on(banner, new NotNullValidator("轮播图"))
                .on(banner.getImgUrl(), new NotNullValidator("图片地址"))
                .on(banner.getCategoryId(), new NotNullValidator("栏目ID"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        banner.setAddTime(new Date());
        banner.setAdminId(getCurrentUser().getId());
        banner.setAdminName(getCurrentUser().getUsername());
        banner.setDeleted(false);
        banner.setPushSort(banner.getPushSort()==null?10000:banner.getPushSort());
        banner.setPushStatus(banner.getPushStatus()==null?1:banner.getPushStatus());
        bannerService.save(banner);
        return ResponseUtil.ok();
    }

    /**
     * @api {POST} /admin/banner/update 4.4 更新轮播图
     * @apiName banner update
     * @apiGroup banner
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 轮播图ID
     * @apiParam {int} categoryId 栏目ID（只有主栏目需要设置轮播图）
     * @apiParam {int} siteId 站点ID（站点的轮播图传这个）
     * @apiParam {String} imgUrl 图片地址
     * @apiParam {int} [pushStatus] 是否展示（默认展示1，不展示0）
     * @apiParam {int} [pushSort] 展示顺序（越大越靠前，默认最大10000）
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:banner:update")
    @RequiresPermissionsDesc(menu={"轮播图管理" , "轮播图设置"}, button="更新轮播图")
    @PostMapping("/update")
    public Object update(@RequestBody GuopuBanner banner) {
        ComplexResult check = FluentValidator.checkAll()
                .on(banner, new NotNullValidator("轮播图"))
                .on(banner.getId(), new NotNullValidator("轮播图ID"))
                .on(banner.getImgUrl(), new NotNullValidator("图片地址"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        banner.setAdminId(getCurrentUser().getId());
        banner.setAdminName(getCurrentUser().getUsername());
        banner.setUpdateTime(new Date());
        banner.setDeleted(false);
        banner.setPushSort(banner.getPushSort()==null?10000:banner.getPushSort());
        banner.setPushStatus(banner.getPushStatus()==null?1:banner.getPushStatus());
        bannerService.updateById(banner);
        return ResponseUtil.ok();
    }

    /**
     * @api {POST} /admin/banner/delete 4.5 删除轮播图
     * @apiName banner delete
     * @apiGroup banner
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 轮播图id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @RequiresPermissions("admin:banner:delete")
    @RequiresPermissionsDesc(menu={"轮播图管理" , "轮播图设置"}, button="删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody GuopuBanner banner) {
        Integer id = banner.getId();
        if (id == null) {
            return ResponseUtil.fail("ID不能为空");
        }
        bannerService.removeById(id);
        return ResponseUtil.ok();
    }

}

